package com.scs.application.core.utils;

import com.scs.application.core.global.GlobalParamService;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @description:
 */
public class CookieUtils {


    public static void clearAllCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                c.setMaxAge(0);
                response.addCookie(c);
            }
        }
    }

    public static void addCookie(HttpServletResponse response, String name, String value) {
        addCookie(response, name, value, null);
    }

    public static void addCookie(HttpServletResponse response, String name, String value, Date expiredTime) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
//        cookie.setHttpOnly(true);
        String domain = GlobalParamService.getInstance().getDomain();
        cookie.setDomain(StringUtils.defaultString(domain, "localhost"));
        if (expiredTime == null) {
            cookie.setMaxAge(-1);
        } else {
            int maxAge = ((int) (expiredTime.getTime() - System.currentTimeMillis()) / 1000);
            cookie.setMaxAge(maxAge);
        }

        response.addCookie(cookie);
    }

    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        if (cookie == null) {
            return null;
        }
        return cookie.getValue();
    }

    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase(name)) {
                return cookie;
            }
        }
        return null;
    }
}

